package com.iocup.keybastion.core.store;


import com.iocup.keybastion.exception.SessionException;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 内存存储session
 * @author xyjxust
 * @create 2022/3/4 14:33
 **/
public class InMemoryCacheStore extends AbstractSessionStore{
    private final ExpiringMap<String, Object> cache = ExpiringMap.builder().expiration(100*12*30,TimeUnit.DAYS).variableExpiration()
            .expirationPolicy(ExpirationPolicy.CREATED)
            .build();

    @Override
    public void setValue(String key, Object value, long expire) {
        if (StringUtils.isBlank(key) || value == null) {
            throw new SessionException("key或者value不能为空");
        }
        if (expire == NO_EXPIRE) {
            cache.put(key, value);
            return;
        }
        cache.put(key, value, expire, TimeUnit.SECONDS);
    }

    @Override
    public void updateValue(String key, Object value) {
        long expireTime = getTimeout(key);
        if (expireTime == NOT_KEY) {
            return;
        }
        if (expireTime == NO_EXPIRE) {
            cache.put(key, value);
        }
        cache.put(key, value, expireTime, TimeUnit.SECONDS);
    }

    @Override
    public void setExpire(String key, long expire) {
        if (cache.containsKey(key)) {
            cache.setExpiration(key, expire, TimeUnit.SECONDS);
        }
    }

    @Override
    public <T> T getValue(String key) {
        if (cache.containsKey(key)) {
            return (T) cache.get(key);
        }
        return null;
    }

    @Override
    public void removeValue(String key) {
        cache.remove(key);
    }

    @Override
    public long getTimeout(String key) {
        if (!cache.containsKey(key)) {
            return NOT_KEY;
        }
        return cache.getExpectedExpiration(key);
    }

    @Override
    public List<String> queryPrefixKey(String prefKey, int start, int size) {
        return searchList(cache.keySet(),prefKey,start,size);
    }




    public static void main(String[] args){
        CacheStore cacheStore = new InMemoryCacheStore();
        cacheStore.setValue("rrr","fff",-1);
        while (true){
            System.out.println(cacheStore.getTimeout("rrr"));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
           cacheStore.setExpire("rrr",60);
        }
    }
}
